package com.test.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition 的 await 和 signal
 *
 * await和signal必须在lock中执行，成对出现
 * 先await后signal
 */
public class ConditionDemo {

    static Lock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void main(String[] args) {

        new Thread(()->{
            lock.lock();
            try{
                System.out.println(Thread.currentThread().getName()+"\t"+"----come In");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                lock.unlock();
            }
            System.out.println(Thread.currentThread().getName()+"\t"+"------被唤醒");
        },"A").start();

        new Thread(()->{
            lock.lock();
            try{
                condition.signal();
                System.out.println(Thread.currentThread().getName()+"\t"+"-------通知");
            }finally {
                lock.unlock();
            }
        },"B").start();
    }

}
